package com.sportwise.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sportwise.domain.User;
import com.sportwise.service.AccountService;

@Controller
public class LoginController {

	private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private AccountService accountService;
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/sportwise/person", method = RequestMethod.GET)
	@ResponseBody
	public User getPersonDetails() {
		LOG.info("Welcome home! the client locale");

		User user = new User("Siddharth Bellur", "siddharth.bellur@gmail.com");
		LOG.debug("Record inserted...");
		this.accountService.addAccount(user);

		return user;
	}

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/sportwise/login", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		LOG.info("Welcome home! the client locale is "+ locale.toString());

		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

		String formattedDate = dateFormat.format(date);

		model.addAttribute("serverTime", formattedDate );

		return "login";
	}

	@RequestMapping(value = "/sportwise/register", method = RequestMethod.POST)
	@ResponseBody
	public WebResponse<Boolean> register(@RequestParam("displayName") String displayName, @RequestParam("email") String email) {
		LOG.info("displayname and email", displayName, email);
		User newUser = new User(displayName, email);
		final int count = this.accountService.addAccount(newUser);
		if (count == 1) {
			//the user got created successfully.
			return new WebResponse<Boolean>(true);
		}
		return new WebResponse<Boolean>(false);
	}

}
